package com.mobile.android.connectionmanager;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.util.Log;

public class HttpRequest implements Runnable {

	private String m_Url;
	private Context m_Context;
	private Handler m_handler;
	private boolean m_isComplete = true;

	public static final int SUCCESS 		= 0;
	public static final int ERROR 			= -1;
	public static final int TIMEOUT_REQUEST = -2;
	Thread myThread; 

	public HttpRequest() {
	}

	public HttpRequest( String aUrl, Context aContent, Handler aHandler ) {
		this.m_Url = aUrl;
		this.m_Context = aContent;
		this.m_handler = aHandler;
	}

	public void setUrl( String aUrl ) {
		this.m_Url = aUrl;
	}
	
	public void setContext( Context aContent ) {
		this.m_Context = aContent;
	}

	public void setHandler( Handler aHandler ) {
		this.m_handler = aHandler;
	}

	public boolean isComplete() {
		return m_isComplete;
	}

	public void sendRequest() {
		m_isComplete = false;
		myThread = new Thread(this); 
	    myThread.start();
	}

	@Override
	public void run() {

		try {
			request();
		} catch (Exception ex) {}

		m_isComplete = true;
	}

	public void request() throws Exception {

		if ( !ConnectionManager.isNetworkAvailable( this.m_Context ) ) {
			// alert: error is not connection yet
			Log.d("[HttpRequest]", "=====Disconnected==== ");
			Message msg = m_handler.obtainMessage();
			msg.what = ERROR;
			m_handler.sendMessage(msg);
			return;
		}

		String result = null;
		Log.d("[HttpRequest]", "url = " + m_Url);
		HttpGet request = new HttpGet( this.m_Url );
		Message msg = m_handler.obtainMessage();

		HttpParams httpParams = new BasicHttpParams();
		int some_reasonable_timeout = (int) (30 * DateUtils.SECOND_IN_MILLIS);
		HttpConnectionParams.setConnectionTimeout(httpParams, some_reasonable_timeout);
		HttpConnectionParams.setSoTimeout(httpParams, some_reasonable_timeout);
		DefaultHttpClient client = new DefaultHttpClient(httpParams);

		try
		{
			//CookieStore myCookieStore =  client.getCookieStore();
			//BasicClientCookie newCookie = new BasicClientCookie("django_language", "de");
			//myCookieStore.addCookie(newCookie);
			//client.setCookieStore(myCookieStore);
			HttpResponse response = client.execute(request);
			StatusLine status = response.getStatusLine();

			if ( status.getStatusCode() == HttpStatus.SC_OK )
			{
			    ResponseHandler<String> responseHandler = new BasicResponseHandler();
			    result = responseHandler.handleResponse(response);
			    msg.obj = result;
			    msg.what = SUCCESS;
				m_handler.sendMessage(msg);
			}
			else
			{
			    msg.what = ERROR;
				m_handler.sendMessage(msg);
			}
		}
		catch (ClientProtocolException e)
		{
			Log.e("HttpRequest", "HTTP Error", e);
			msg.what = ERROR;
			m_handler.sendMessage(msg);
		}
		catch (IOException e)
		{
			Log.e("HttpRequest", "Connection Error", e);
			msg.what = ERROR;
			m_handler.sendMessage(msg);
		}
		finally
		{
			client.getConnectionManager().shutdown();
		}
	}
}